package com.sun.springCache.manager;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.Cache;
import org.springframework.cache.support.SimpleValueWrapper;

public class MyCache implements Cache {

	private static final Logger LOG = LoggerFactory.getLogger(MyCache.class);
	private String name;
	private Map<Object, Object> store = new HashMap<>();
	private static Set<String> noCacheCategoryNames = new HashSet<String>(); 
	private static Set<String> noCacheKeys = new HashSet<String>(); 
	
	public MyCache() {
	}

	public MyCache(String name) {
		this.name = name;
	}

	@Override
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public Map<Object, Object> getNativeCache() {
		return store;
	}

	@Override
	public ValueWrapper get(Object key) {
		ValueWrapper result = null;
		Object thevalue = store.get(key);
		
		if (thevalue != null) {
			result = new SimpleValueWrapper(thevalue);
		}
		
		return result;
	}

	@Override
	public void put(Object key, Object value) {
		if(key instanceof String){
			String keyStr = (String)key;
			if(noCacheKeys.contains(keyStr))return;
			for (String noCacheCategoryName : noCacheCategoryNames) {
				if(keyStr.startsWith(noCacheCategoryName+"#")){
					noCacheKeys.add(keyStr);
					return;
				}
			}
		}
		store.put(key, value);
		LOG.info("加入缓存key:[{}]", key);
	}

	@Override
	public void clear() {
		LOG.info("clear categoryName = {}",name);
		store.clear();
	}

	/**
	 * 增加按规则前缀规则的清理方法 ，key=categoryName 
	 * 规则：categoryName#xxx
	 * @see org.springframework.cache.concurrent.ConcurrentMapCache#evict(java.lang.Object)
	 */
	@Override
	public void evict(Object key) {
//这里是一个很不错的方法，把系统中的一个常量（categoryName--n(key:value)以categoryName作为清理key，以n（categoryName--key）作为缓存key）
//		if(key instanceof String && ((String) key).endsWith("#")){
//			for (Iterator<Object> keyIterator = store.keySet().iterator(); keyIterator.hasNext();) {
//				Object storeKey = keyIterator.next();
//				if((storeKey instanceof String) && String.class.cast(storeKey).startsWith((String)key)){
//					keyIterator.remove();
//				}
//			}
//		}else{
//			store.remove(key);
//		}
		store.remove(key);
		LOG.info("执行缓存清理，name={},key={}",getName(),key);
	}

	
	/**
	 * 标记为不缓存
	 * @param categoryName
	 */
	public static void addNoCache(String categoryName){
		noCacheCategoryNames.add(categoryName);
	}
}
